package codegenplugin.popup.actions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import cn.com.zte.ant.model.AntModelLoader;
import cn.com.zte.ant.model.AntModelObjectPartner;
import cn.com.zte.ngbc.frw.model.ModelFileAware;
import cn.com.zte.ngbc.frw.model.generator.GeneratorTypeManager;
import cn.com.zte.ngbc.frw.model.generator.ModelJavaGenerator;
import cn.com.zte.ngbc.frw.model.generator.ModelJavaGenerator.JavaClassModel;
import xml.XmlUtil;
import codegen.CodegenUtil;
import console.ConsoleFactory;

public class CodegenAction implements IObjectActionDelegate {

	private Shell shell;
	private ISelection selection;
	
	/**
	 * Constructor for Action1.
	 */
	public CodegenAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {		
		
		//读取选定的配置文件	
		IStructuredSelection selection =(IStructuredSelection) this.selection;		

		ConsoleFactory.printToConsole("--------Start Coding--------", true);
		
		for(Object element:selection.toList()){
			org.eclipse.core.internal.resources.File file1 = (org.eclipse.core.internal.resources.File)element;	
			IResource iproject= file1.getProject();
			
			String fullpath = file1.getLocationURI().getPath();
			try {
				String configfilepath=fullpath;
				ConsoleFactory.printToConsole("...load coding config "+configfilepath, true);
			    Set<File> ret11 = new HashSet();
			    
			    String configfilepath1=configfilepath.substring(0,configfilepath.lastIndexOf("/src/main/resources"));
			    configfilepath=configfilepath1.substring(0,configfilepath1.lastIndexOf("/"));
			    
			    Collection<File> filesCollection = FileUtils.listFiles(new File(configfilepath), new String[] { "xml"}, true);
				if (filesCollection.size() >0 && filesCollection !=null) {
					Map listWithoutDup=new HashMap();
					for (File file : filesCollection) {
						String xmlFilePath = file.getAbsolutePath();
						if(xmlFilePath.indexOf("/src/main/resources/")>0)
						{	
							listWithoutDup.put(xmlFilePath.substring(xmlFilePath.indexOf("/src/main/resources/")), xmlFilePath);
						    // ret11.add(new File(xmlFilePath));
						}
					}
					for (Object object : listWithoutDup.values()) {
						//System.out.println(object);
						ret11.add(new File((String) object));
					}
				}
				
			    Set<File> reta = new HashSet();
			    reta.add(new File(fullpath));
			    AntModelLoader m = new AntModelLoader(reta,ret11);
			    AntModelObjectPartner.setModelLoader(m);
			    for (Object model1 : m.getSourceModels())
			      {
			    	String javacontent="";
			    	JavaClassModel ret;
			        ModelFileAware modelFile = (ModelFileAware)model1;
					GeneratorTypeManager.GeneratorType gt = GeneratorTypeManager.getInstance().getGeneratorType(modelFile.getClass());
					if(gt !=null){
						 ret = gt.creatJavaClassModelWithoutContent(modelFile);
						 javacontent= gt.getJavaContent(ret, modelFile);
						 ConsoleFactory.printToConsole(javacontent, true);
						    File file = null;
						    String packagePath = ret.getPackage();
						    if ((packagePath == null) || (packagePath.trim().length() == 0))
						    {
						        //没包提示
						    	ConsoleFactory.printToConsole("package  is null", true);
						    }
						    else
						    {
						      if (packagePath.indexOf(".") > 0) {
						        packagePath = packagePath.replace(".", "/");
						      }
						      file = new File(configfilepath1+"/target/gen", packagePath);
				    		 ConsoleFactory.printToConsole(file.getPath(), true);
						      file.mkdirs();
						    }
						    File javaFile = new File(file, ret.getClassName() + ".java");
						    if (!javaFile.exists()) {
						      javaFile.createNewFile();
						    }
						    FileUtils.write(javaFile, javacontent, "UTF-8");
						 
						 
					}else{
			        	ret =	ModelJavaGenerator.generateClassImpl(modelFile,true);
			        	javacontent=ret.getJavaContent();
			        	ConsoleFactory.printToConsole(javacontent, true);
					    File file = null;
					    String packagePath = ret.getPackage();
					    if ((packagePath == null) || (packagePath.trim().length() == 0))
					    {
					        //没包提示
					    	ConsoleFactory.printToConsole("package  is null", true);
					    }
					    else
					    {
					      if (packagePath.indexOf(".") > 0) {
					        packagePath = packagePath.replace(".", "/");
					      }
					      file = new File(configfilepath1+"/src/main/java", packagePath);
			    		 ConsoleFactory.printToConsole(file.getPath(), true);
					      file.mkdirs();
					    }
					    File javaFile = new File(file, ret.getClassName() + ".java");
					    if (!javaFile.exists()) {
					      javaFile.createNewFile();
					      FileUtils.write(javaFile, javacontent, "UTF-8");
					    }else{
					    	File javaFile1 = new File(file, ret.getClassName() + ".java.new");
					    	javaFile1.createNewFile();
					    	FileUtils.write(javaFile1, javacontent, "UTF-8");
					    }
					
			        
					}
					
					

			      }
			    //刷新工程
			    iproject.refreshLocal(IResource.DEPTH_INFINITE,null);	   
			} catch (Exception e) {
				ConsoleFactory.printToConsole(e.getMessage(), true);
				e.printStackTrace();
			}
			
			
		}
		
		ConsoleFactory.printToConsole("--------Finish Coding--------", true);
		
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		this.selection=selection;
	}

}
